package com.adwin.addcoin.ui.task

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.webkit.WebView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.R
import com.adwin.addcoin.base.BaseActivity
import com.adwin.addcoin.base.BaseWebView
import com.adwin.addcoin.databinding.ActivityTaskDetailBinding
import com.adwin.addcoin.repository.bean.TaskStage
import com.adwin.addcoin.ui.adapter.TaskDetailItemAdapter
import com.adwin.addcoin.utils.FlowKeyUtils
import com.adwin.addcoin.utils.TaskStatusNet
import com.adwin.addcoin.utils.installRepost
import com.adwin.addcoin.utils.startBrowser
import com.bumptech.glide.Glide
import com.cashbird.app.infra.utils.FlowBus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * 任务详情页面
 */
class TaskDetailActivity:BaseActivity<ActivityTaskDetailBinding,TaskDetailModel>(
    TaskDetailModel::class.java
) {
    private var offerId = ""
    private var activityId = -1L
    private var taskName = ""
    private var taskDecs = ""
    private var stages = ArrayList<TaskStage>()
    private var linkUrl = ""
    private var webView:BaseWebView? = null
    private var trackingUrl = ""
    private var stepNum:Long = 0
    private var coinNum:Long = 0



    companion object{
        private const val activityIdName = "activityId"
        private const val offerIdName = "offerId"
        private const val taskNameTitle = "taskName"
        private const val taskDecsTitle = "taskDecs"
        private const val taskIconTitle = "taskIcon"
        fun start(mContext:Context,taskId:String = "",taskType:Long = -1,taskName:String,taskDecs:String,taskIcon:String){
            val intent = Intent()
            intent.setClass(mContext,TaskDetailActivity::class.java)
            intent.putExtra(activityIdName,taskType);
            intent.putExtra(offerIdName,taskId)
            intent.putExtra(taskNameTitle,taskName)
            intent.putExtra(taskDecsTitle,taskDecs)
            intent.putExtra(taskIconTitle,taskIcon)
            mContext.startActivity(intent)
        }
    }

    override fun onStart() {
        super.onStart()
        TaskStatusNet.startStepStatus()
        setChangeTask()
    }

    override fun inflater(): ActivityTaskDetailBinding {
       val binding = ActivityTaskDetailBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        return binding
    }

    override fun initActivity() {
        fullScreen(this)
        webView = BaseWebView(this.applicationContext)
        activityId =  intent.getLongExtra(activityIdName, 0L)
        offerId = intent.getStringExtra(offerIdName)?:""
        taskDecs = intent.getStringExtra(taskDecsTitle)?:""
        taskName = intent.getStringExtra(taskNameTitle)?:""
        binding.rvTaskDetail.adapter = TaskDetailItemAdapter(this,stages)
        binding.rvTaskDetail.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        viewModel?.taskDetailBean?.observe(this){
            it?.let {taskDetail ->
                MainScope().launch(Dispatchers.Main) {
                    binding.clTaskLoading.visibility = View.GONE
                    if (taskDetail.isInProgress == 0){
                        binding.rvTaskDetail.visibility = View.GONE
                        binding.tvStartTask.text = "Start Mission"
                        binding.ivTaskDetailCurrent.setImageResource(R.mipmap.task_detail_current_get)
                        val drawable = resources.getDrawable(R.mipmap.task_detail_current_coins)
                        drawable.setBounds(0,0,drawable.minimumWidth,drawable.minimumHeight)
                        binding.tvTaskDetailCurrentCoins.setCompoundDrawables(null,null,drawable,null)
                        taskDetail.currentStep?.let {
                            binding.tvTaskDetailCurrentTitle.text ="LV${it.stepNum}"
                        }
                    }else if (taskDetail.isInProgress == 1){
                        if (taskDetail.currentStep !=null){
                            coinNum = taskDetail.currentStep.coinNum
                        }
                        stepNum = taskDetail.stepId?.toLong()?:0
                        binding.ivTaskDetailCurrent.setImageResource(R.mipmap.task_detail_current_start)
                        binding.rvTaskDetail.visibility = View.VISIBLE
                        binding.tvStartTask.text = "Get"
                        binding.pbCurrentProgress.progress = 30
                        val drawable = resources.getDrawable(R.mipmap.task_detail_start_current_coins)
                        drawable.setBounds(0,0,drawable.minimumWidth,drawable.minimumHeight)
                        binding.tvTaskDetailCurrentCoins.setCompoundDrawables(null,null,drawable,null)
                        taskDetail.currentStep?.let {
                            binding.tvTaskDetailCurrentTitle.text ="STEP${it.stepNum}"
                        }
                    }else{
                        binding.tvTaskDetailCurrentTitle.visibility = View.GONE
                        binding.tvStartTask.visibility = View.GONE
                        binding.ivTaskDetailCurrent.visibility = View.GONE
                        binding.tvTaskDetailCurrentCoins.visibility = View.GONE
                        binding.tvTaskDetailCurrentDesc.visibility = View.GONE
                        binding.viewCurrentTaskDrawable.visibility = View.GONE
                        binding.viewCurrentLine.visibility = View.GONE
                        binding.pbCurrentProgress.visibility = View.GONE
                        binding.tvCurrentGetCoinsTitle.visibility = View.GONE
                    }
                    trackingUrl = taskDetail.trackingUrl
                    linkUrl = taskDetail.linkUrl
                    if (activityId > 0){
                        offerId = taskDetail.orderId.toString()
                    }
                    Glide.with(this@TaskDetailActivity).load(taskDetail.iconUrl).error(R.mipmap.addcoins_acquiesce_icon).placeholder(R.mipmap.addcoins_acquiesce_icon).into(binding.ivTaskIcon)
                    binding.tvTaskName.text = taskName
                    binding.tvTaskDescription.text = taskDecs
                    binding.pbTotalProgress.progress = taskDetail.percentage
                    binding.tvTotalTaskProgressNumber.text = "${taskDetail.percentage}%"
                    binding.tvTaskDetailCurrentDesc.text = taskDetail.currentStep?.stepDesc
                    binding.tvTaskDetailCurrentCoins.text = "${taskDetail.currentStep?.coinNum}"
                    if (taskDetail.undoneSteps != null&&taskDetail.undoneSteps.size>0){
                        binding.tvMissionDetails.visibility = View.VISIBLE
                        binding.tvEarnings.visibility = View.VISIBLE
                        stages.clear()
                        stages.addAll(taskDetail.undoneSteps)
                        binding.rvTaskDetail.visibility = View.VISIBLE
                    }else{
                        binding.rvTaskDetail.visibility = View.GONE
                        binding.tvEarnings.visibility = View.GONE
                        binding.tvMissionDetails.visibility = View.GONE
                    }
                    binding.rvTaskDetail.adapter?.notifyDataSetChanged()
                }
            }
        }
        viewModel?.isChangTask?.observe(this){
            if (it){
                lifecycleScope.launch {
                    delay(800)
                    FlowBus.with<String>(FlowKeyUtils.taskChange).post("")
                }
                setChangeTask()
            }
        }

        FlowBus.with<Long>(FlowKeyUtils.taskStageChange).register(lifecycle){
            setChangeTask()
        }
        binding.tvStartTask.setOnClickListener {
            if (binding.tvStartTask.text == "Get"){
                MainScope().launch (Dispatchers.Main){
                    if (!TextUtils.isEmpty(trackingUrl)){
                        webView?.loadUrl(trackingUrl)
//                        viewModel?.sendTask(trackingUrl)
                    }
                }
                TaskStatusNet.addTaskStage(stepNum,coinNum)
                startBrowser(linkUrl)
                MainScope().launch(Dispatchers.IO) {
                    val obj = JSONObject()
                    if (activityId > 0){
                        obj.put("taskid",activityId)
                        obj.put("taskType","activity")
                    }else{
                        obj.put("taskid",offerId)

                        obj.put("taskType","task")
                    }
                    obj.put("linkUrl",linkUrl)
                    installRepost("openStartTask",obj)
                }
            }else{
                MainScope().launch(Dispatchers.IO) {
                    val obj = JSONObject()
                    if (activityId > 0){
                        obj.put("taskid",activityId)
                        obj.put("taskType","activity")
                    }else{
                        obj.put("taskid",offerId)

                        obj.put("taskType","task")
                    }
                    obj.put("linkUrl",linkUrl)
                    installRepost("startTask",obj)
                }
                viewModel?.startTask(offerId,activityId)
            }
        }
        binding.ivTaskReturn.setOnClickListener {
            finish()
        }
    }

    override fun onResume() {
        super.onResume()

    }

    override fun onPause() {
        super.onPause()

    }

    override fun onDestroy() {
        if (webView!= null){
            webView?.destroy()
            webView = null
        }
        super.onDestroy()
    }

    private fun setChangeTask(){
        lifecycleScope.launchWhenResumed {
            if (activityId > 0){
                viewModel?.getActivityDetail(activityId)
            }else{
                viewModel?.getTaskDetail(offerId)
            }
        }
    }
}